package com.ssh.dao.impl;

import com.ssh.dao.UserDao;
import com.ssh.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户 dao 的实现类
 *
 * @author yang
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.openSession();
    }

    /**
     * 根据 id 获取一个
     *
     * @param id id
     * @return 实体类
     */
    @Override
    public User load(Integer id) {
        return (User) getSession().get(User.class, id);
    }

    @Override
    public User load(Integer id, String password) {

        final User load = load(id);
        if (load==null|| !load.getPassword().equals(password)){
            // 没有此 id 或 密码不一致
            return null;
        }
        return load;
    }


    /**
     * 保存一个
     *
     * @param entity 实体类
     * @return 影响的行数
     */
    @Override
    public Integer save(User entity) {
        Session session = getSession();
        int n = (Integer) session.save(entity);
        session.flush();
        return n;
    }

    /**
     * 更新
     */
    @Override
    public void flush() {
        getSession().flush();
    }

}
